package dome_005;

import java.util.concurrent.TimeUnit;

/**
 * <p>Description: [程序在执行过程中，如果出现异常，默认情况锁会被释放]</p>
 * Created on 2020/12/3
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class Dome005_01 {
    int count = 0;

    synchronized void test() {
        System.out.println(Thread.currentThread().getName() + " start......");
        while (true) {
            count++;
            System.out.println(Thread.currentThread().getName() + " count = " + count);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (count == 5) {
                int i = 1 / 0; //此处抛出异常，锁将被释放，要想不被释放，可以在这里进行catch处理，然后让循环继续
            }
        }
    }

    public static void main(String[] args) {
        Dome005_01 dome005_01 = new Dome005_01();

        Runnable r = new Runnable() {
            @Override
            public void run() {
                dome005_01.test();
            }
        };

        new Thread(r, "t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(r, "t2").start();
    }
}
